package com.wbpay.sdk.pay.webpay;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.wbpay.sdk.constant.Constants;
import com.wbpay.sdk.framework.IPayFunction;
import com.wbpay.sdk.framework.PayResult;
import com.wbpay.sdk.framework.ResponseCallback;
import com.wbpay.sdk.http.Response;
import com.wbpay.sdk.model.SdkInfo;
import com.wbpay.sdk.params.PayParams;
import com.wbpay.sdk.pay.IPay;
import com.wbpay.sdk.request.IPayRequest;
import com.wbpay.sdk.utils.Log;
import com.wbpay.sdk.utils.Utils;
import com.wbpay.sdk.widget.JyouActivity;
import com.wbpay.sdk.wrapper.SwiftPayWrapper;

import org.json.JSONObject;

import java.util.Map;
import java.util.TreeMap;

/**
 * 威富通
 */
public class SwiftPay implements IPay {
    private Context mContext;
    private IPayFunction mPayFunction;

    @Override
    public void init(Context context, IPayFunction f) {
        mContext = context;
        mPayFunction = f;
    }

    @Override
    public void pay(final PayParams payParams) {
        if (payParams == null) {
            String desc = mContext.getString(Utils.getStringId(mContext, "jy_null_payparams"));
            mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, desc, this);
            return;
        }
        // 请求服务器获取威富通的支付url
        if (mPayFunction != null) {
            IPayRequest payRequest = mPayFunction.getPayRequest();
            if (payRequest == null) {
                mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, mContext.getString(Utils.getStringId(mContext, "jy_fetch_payargs_error")), this);
                return;
            }
            final IPay iPay = this;
            payRequest.requestSwiftPayUrl(payParams, new ResponseCallback<JSONObject>() {
                @Override
                public void onCallback(Response<JSONObject> response) {
                    String swiftPayUrl = null;
                    String errorMsg = null;
                    try {
                        swiftPayUrl = response.getObj().getString("pay_info");
                    } catch (Exception e) {
                        errorMsg = response.getMsg();
                        // TODO:服务器联调之前的测试代码
                        // swiftPayUrl = generateSwiftPayUrlForTest("http://wap.9you-nj.cn/wap/cash", payParams);
                    }

                    if (!TextUtils.isEmpty(swiftPayUrl)) {
                        startSwiftPay(payParams, swiftPayUrl);
                    } else {
                        if (TextUtils.isEmpty(errorMsg)) {
                            errorMsg = mContext.getString(Utils.getStringId(mContext, "jy_fetch_payargs_error"));
                        }
                        mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, errorMsg, iPay);
                    }
                }
            });
        }
    }

    private void startSwiftPay(PayParams payParams, String swiftPayUrl) {
        String channelId = SdkInfo.get(mContext).getChannel();
        String appId = SdkInfo.get(mContext).getAppId();

        String broadcastAction = setupAndGetBroadcast();
        Intent intent = new Intent(mContext, JyouActivity.class);
        intent.putExtra(Constants.EXTRA_AWCN, SwiftPayWrapper.class.getName());
        intent.putExtra(Constants.EXTRA_CALLBACK, broadcastAction);
        intent.putExtra(Constants.EXTRA_FULLSCREEN, Utils.isFullScreen(mContext));

        intent.putExtra("server", payParams.getServer());
        intent.putExtra("price", payParams.getPrice());
        intent.putExtra("attach", payParams.getAttach());
        intent.putExtra("subject", payParams.getSubject());
        intent.putExtra("order", payParams.getOrder());
        intent.putExtra("body", payParams.getBody());
        intent.putExtra("pay_url", swiftPayUrl);
        intent.putExtra("channel", channelId);
        intent.putExtra("appid", appId);
        try {
            mContext.startActivity(intent);
        } catch (Exception e) {
            if (mPayFunction != null) {
                String desc = mContext.getString(Utils.getStringId(mContext, "jy_unknown"));
                mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, desc, this);
            }
        }
    }

    /**
     * 生成测试支付URL的代码
     * @param url
     * @param payParams
     * @return
     */
    private String generateSwiftPayUrlForTest(String url, PayParams payParams) {
        Map<String, String> map = new TreeMap<String, String>();
        map.put("server", payParams.getServer());
        map.put("price", payParams.getPrice());
        map.put("attach", payParams.getAttach());
        map.put("subject", payParams.getSubject());
        map.put("order", payParams.getOrder());
        map.put("body", payParams.getBody());
        map.put("itemid", payParams.getItemid());

        /***********/
        String channel = "000000";
        String appid = "1";
        String uin = "25";
        String amount = map.get("price");
        String appkey = "91ab1d35a320d62b5d2ab33223312184";
        String sign = Utils.string2MD5(channel + appid + uin + amount + appkey);
        map.put("channel", channel);
        map.put("appid", appid);
        map.put("app_uid", uin);
        map.put("amount", amount);
        map.put("sign", sign);
        /***************/
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry != null && !TextUtils.isEmpty(entry.getValue())) {
                builder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        if (builder.length() > 0) {
            return url + "?" + builder.toString();
        }
        return url;
    }

    @Override
    public String getPayName() {
        // 使用微信图标及名称
        return mContext.getString(Utils.getStringId(mContext, "jy_swift_pay"));
        // return mContext.getString(Utils.getStringId(mContext, "jy_pay_list_activity_wx_pay"));
    }

    @Override
    public int getPayType() {
        return PAY_TYPE_SWIFT;
    }

    @Override
    public boolean checkPayAvailable() {
        return false;
    }

    @Override
    public int getPayIcon() {
        // 使用微信图标及名称
        return Utils.getDrawableId(mContext, "jy_swift_icon");
        // return Utils.getDrawableId(mContext, "jy_wx");
    }

    @Override
    public String getPayDesc() {
        // 使用微信图标及名称
        // return mContext.getString(Utils.getStringId(mContext, "jy_swift_desc"));
        return mContext.getString(Utils.getStringId(mContext, "jy_wxpay_desc"));
    }

    @Override
    public String toString() {
        return getPayName();
    }

    /**
     * 设置威富通支付回调广播
     *
     * @return
     */
    private String setupAndGetBroadcast() {
        try {
            // 注销之前注册的广播
            mContext.unregisterReceiver(mBroadcastReceiver);
        } catch (Exception e) {
        }
        String action = mContext.getPackageName() + ".intent.action.SWIFTPAYRESULT";
        IntentFilter filter = new IntentFilter(action);
        mContext.registerReceiver(mBroadcastReceiver, filter);
        return action;
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mContext.unregisterReceiver(mBroadcastReceiver);
            int error = -1;
            String desc = null;
            if (intent != null) {
                error = intent.getIntExtra("RESULT_CODE", -1);
                desc = intent.getStringExtra("RESULT_DESC");
            }
            Log.d(Log.TAG, "error : " + error + " , desc : " + desc);
            processSwiftPayResult(error, desc);
        }
    };

    private void processSwiftPayResult(int error, String desc) {
        if (mPayFunction != null) {
            mPayFunction.notifyPayResult(error, desc, this);
        }
    }
}
